<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail" layout='horizontal'>
        <a-row :span="24">
          <a-col :span="24">
          <a-button
            type="primary"
            icon=""
            size="small"
            @click="addGoods(1)">
            包装材料
          </a-button>
          <erp-goods-list-model ref="selectGoodsList"
                                :modalWidth="modalWidth"
                                :category="category"
                                @goodsOk="goodsOk"
                                checkval='checkbox'>
          </erp-goods-list-model>
          </a-col>
          <a-col :span="24">
            <!-- 表格 -->
            <a-table bordered :data-source="model.erpGoodsPackageList"
                     :columns="warpMaterial.columns"
                     :rowKey="record=>record.id"
                     :pagination="false">
              <template slot="number" slot-scope="text, record">
                <editable-cell :text="text" @change="onCellChange(record, 'number', $event)"></editable-cell>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  title="确认删除?"
                  @confirm="() => onDelete(record.id)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <!--                <a @click="handleEdit(record)">保存</a>-->
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row :span="24">
          <a-col :span="24">
          <a-button
            type="primary"
            icon=""
            size="small"
            @click="addGoods">
            产品报价
          </a-button>
          </a-col>
          <a-col :span="24">
            <a-table bordered :data-source="model.productQuotationList"
                     :columns="productQuote.columns"
                     :rowKey="record=>record.id"
                     :pagination="false">
              <template slot="number" slot-scope="text, record">
                <editable-cell :text="text" @change="onCellChange(record, 'number', $event)"></editable-cell>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm
                  title="确认删除?"
                  @confirm="() => onDelete(record.id)"
                >
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <!-- <a @click="handleEdit(record)">保存</a>-->
              </template>
            </a-table>
          </a-col>
        </a-row>
        <a-row :span="24">
          <a-col :span="24">
            <a-form-model-item label="报价备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="quotationRemarks">
              <a-textarea v-model="model.quoteRemark" placeholder="" :rows="4" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="财务备录" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="financialRemarks">
              <a-textarea v-model="model.financeRemark" placeholder="" :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :span="24">
          <a-col :span="12">
            <a-form-model-item label="汇率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exchangeRate">
              <a-input-number v-model="model.exchangeRate" placeholder="请输入汇率" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="税率" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxRate">
              <a-input-number v-model="model.rate" placeholder="请输入税率" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="客户其他费用(如版费等)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherExpenses">
              <a-input-number v-model="model.otherExpenses" placeholder="请输入客户其他费用(如版费等)" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="客户其他费用说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="otherRemarks">
              <a-input v-model="model.otherExpensesDes" placeholder="请输入客户其他费用说明"  ></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="总金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="amount">
              <a-input-number v-model="model.totalAmount" placeholder="请输入总金额" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import { httpAction, getAction, postAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import ErpGoodsListModel from "@comp/base/modal/ErpGoodsListModal";
  import EditableCell from '@comp/table/EditableCell'

  export default {
    name: 'BussContractRequirementReviewForm',
    components: {
      ErpGoodsListModel,
      EditableCell
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      dataId: {
        type: String
      },
    },
    watch: {
      dataId(newValue) {
        // 当category变更时，可以进行一些处理
        console.log('Category changed to:', newValue);
        this.model.contractReviewId = newValue;
        console.log(this.model.contractReviewId)
        getAction('/business/bussOutletQuote/queryByReviewId', {id:newValue}).then(res => {
          let erpGoodsList = res.result;
          this.model = Object.assign({}, erpGoodsList);
        })
      }
    },
    data () {
      return {
        description: '出口业务报价单',
        modalWidth: 1000,
        category: '',
        model:{
          contractReviewId: '',
          erpGoodsPackageList: [],
          productQuotationList: [],
        },
        lab: 1,
        warpMaterial:{
          columns: [
            {
              title: '名称',
              dataIndex: 'name',
            },
            {
              title: '规格',
              dataIndex: 'nodeSpec',
            },
            {
              title: '件/吨',
              dataIndex: 'ton',
            },
            {
              title:"规格",
              children:[
                {
                  title: '克数',
                  dataIndex: 'grams',
                },
                {
                  title: '个数',
                  dataIndex: 'number',
                },
              ]
            },
            {
              title:"外包装1",
              children:[
                {
                  title: '个数',
                  dataIndex: 'packageNumber1',
                },
                {
                  title: '单价',
                  dataIndex: 'packageUnitPrice1',
                },
                {
                  title: '金额',
                  dataIndex: 'packageAmount1',
                }
              ]
            },
            {
              title: "外包装2",
              children:[
                {
                  title: '个数',
                  dataIndex: 'packageNumber2',
                },
                {
                  title: '单价',
                  dataIndex: 'packageUnitPrice2',
                },
                {
                  title: '金额',
                  dataIndex: 'packageAmount2',
                }
              ]
            },
            {
              title: "内包装",
              children:[
                {
                  title: '个数',
                  dataIndex: 'innerPackageNumber',
                },
                {
                  title: '单价',
                  dataIndex: 'innerPackageUnitPrice',
                },
                {
                  title: '金额',
                  dataIndex: 'innerPackageAmount',
                }
              ]
            },
            {
              title: '其他',
              dataIndex: 'other',
            },
            {
              title: '包装成本',
              dataIndex: 'packageCost',
            },
            {
              title: '操作',
              dataIndex: 'operation',
              scopedSlots: { customRender: 'operation' },
            },
          ],
        },
        productQuote:{
          columns: [
            {
              title: '名称',
              dataIndex: 'name',
            },
            {
              title: '规格',
              dataIndex: 'nodeSpec',
            },
            {
              title: '件/吨',
              dataIndex: 'ton',
            },
            {
              title: '原料',
              dataIndex: 'material',
            },
            {
              title: '包材',
              dataIndex: 'packageMaterials',
            },
            {
              title: '中间费用',
              dataIndex: 'midExpenses',
            },
            {
              title: '合计',
              dataIndex: 'total',
            },
            {
              title:'出厂价',
              children: [
                {
                  title: '*1.13/1',
                  dataIndex: 'exWorksPrice',
                },
              ]
            },
            {
              title: '陆运费',
              dataIndex: 'landFreight',
            },
            {
              title: '不干胶贴',
              dataIndex: 'adhesiveStickers',
            },
            {
              title: '其他',
              dataIndex: 'other',
            },
            {
              title: '海运费',
              dataIndex: 'seaFreight',
            },
            {
              title: 'coco费用',
              dataIndex: 'cocoExpenses',
            },
            {
              title: '版费',
              dataIndex: 'royalty',
            },
            {
              title: '保费',
              dataIndex: 'insurancePremium',
            },
            {
              title: '印刷费',
              dataIndex: 'printingFee',
            },
            {
              title: '佣金',
              dataIndex: 'commission',
            },
            {
              title: '其他',
              dataIndex: 'other2',
            },
            {
              title: '合计',
              dataIndex: 'total2',
            },
            {
              title: '业务员',
              children: [
                {
                  title: '吨数',
                  dataIndex: 'ywTon',
                },
                {
                  title: '吨价',
                  dataIndex: 'ywTonPrice',
                },
                {
                  title: '件价',
                  dataIndex: 'ywPiecePrice',
                },
                {
                  title: '实际报价',
                  dataIndex: 'ywActualQuote',
                },
                {
                  title: '是否符合政策',
                  dataIndex: 'ywIsCompliantPolicies',
                },
              ]
            },
            {
              title: '操作',
              dataIndex: 'operation',
              scopedSlots: { customRender: 'operation' },
            },
          ],
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
           code: [
              { required: true, message: '请输入评审表编号!'},
           ],
        },
        url: {
          add: "/business/bussOutletQuote/add",
          edit: "/business/bussOutletQuote/edit",
          queryById: "/business/bussOutletQuote/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      console.log(this.dataId);
    },
    methods: {
      tabsChange(activeKey){
        this.tabs.activeKey = activeKey;
      },
      getPfCode() {
        postAction('/sys/fillRule/executeRuleByCode/psbbh', {}).then(res => {
          this.model.code = res.result;
        })
      },
      add () {
        // this.edit(this.modelDefault);
        // // this.getPfCode();
        // console.log("--------")
        // console.log(this.contract)
        // this.model.contractCode = this.contract.code;
        // this.model.customerName = this.contract.customerId_dictText;
        // this.model.customer = this.contract.customer;
        // this.model.weight = this.contract.weight;
        // this.model.weightUnit = this.contract.weightUnit;
        // this.model.payMethod = this.contract.payMethod;
        // this.model.deliveryTime = this.contract.deliveryTime;
        // this.model.contractTime = this.contract.createTime;
        // this.model.desId = this.contract.id;
      },
      edit (record) {
        this.model = Object.assign({}, record);
        // this.visible = true;
      },
      submitForm (id) {
        //提交
        const that = this;
        this.model.contractReviewId = id;
        if(!id){
          that.$message.warning("请先保存合同评审表");
          return ;
        }
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
                this.$emit('my-event', res.message)

              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      addGoods: function(val){
        // 新增物料
        // console.log(this.$refs.selectGoodsList)
        this.lab = val;
        this.$nextTick(()=>{
          this.$refs.selectGoodsList.add();
        })
        // this.$refs.selectGoodsList.add();
        // this.$refs.selectGoodsList.title = "新增";
        // this.$refs.selectGoodsList.disableSubmit = false;
      },
      goodsOk(datas) {
        const _this = this;
        //todo 产品关联配方有问题
        postAction('/base/erpGoods/list/ids', { ids: datas }).then(res => {
          console.log('获取的结果',res.result)
          let erpGoodsList = res.result;
          if(_this.lab ==1){
            _this.pushPackage(erpGoodsList);
          }else{
            _this.pushProductPrice(erpGoodsList);
          }
        })
      },
      pushPackage(erpGoods){
        const _this = this;
        erpGoods.forEach(function(item,index){
          //   console.log(item,index)
          let detail = {};
          detail.goodsId = item.id;
          detail.name = item.name;
          detail.noneSpec = item.noneSpec
          _this.filterPackageId(item.id,_this.model.erpGoodsPackageList);
          _this.model.erpGoodsPackageList.push(detail);
          //   _this.model.erpGoodsPackageList.push(detail);
        })
      },
      pushProductPrice(erpGoods){
        const _this = this;
        erpGoods.forEach(function(item,index){
          //   console.log(item,index)
          let detail = {};
          detail.goodsId = item.id;
          detail.name = item.name;
          detail.noneSpec = item.noneSpec
          _this.filterPackageId(item.id,_this.model.productQuotationList);
          _this.model.productQuotationList.push(detail);
          //   _this.model.erpGoodsPackageList.push(detail);
        })
      },
      filterPackageId(goodsId,obj){
        obj = obj.filter(function(item) {
          return item.goodsId !== goodsId;
        });
      },
      onCellChange(record, dataIndex, value) {
        console.log(this.model.erpGoodsPackageList)
        console.log(record)
        const dataSource = [...this.model.erpGoodsPackageList];
        const target = dataSource.find(item => item.packageCode === record.packageCode);
        // console.log(target,key,dataIndex,value)
        if (record) {
          target[dataIndex] = value;
          this.model.erpGoodsPackageList = dataSource;
        }
      },
      onDelete(key){
        const dataSource = [...this.model.erpGoodsPackageList];
        this.model.erpGoodsPackageList = dataSource.filter(item => item.id !== key);
        // deleteAction('base/erpGoodsFormulaDetail/delete',{id:key}).then(res=>{
        //   if(res.success){
        //
        //   }
        // })

      },
    }
  }
</script>